/*
 * Created on 04/01/2010, 20:26:51
 */
package loja.gui;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JOptionPane;
import loja.dao.CategoriaDao;
import loja.dao.exceptions.BuscaException;
import loja.dominio.Categoria;
import loja.gui.tablemodel.CategoriaTableModel;
import loja.gui.utils.EstadoInterface;

import loja.gui.utils.MessageUtil;
import loja.validacao.CategoriaValidador;
import loja.validacao.Validador;

/**
 *
 * @author Rodrigo
 */
public class CategoriaForm extends javax.swing.JFrame {

    private EstadoInterface inicial;
    private EstadoInterface emAdicao;
    private EstadoInterface emEdicao;
    private EstadoInterface emPesquisa;
    private Categoria categoria;
    private CategoriaDao categoriaDao;
    private CategoriaTableModel model;
    private List<Categoria> cadCategorias;

    public CategoriaForm() {
        try {
            model = new CategoriaTableModel();
            categoriaDao = new CategoriaDao();
            initComponents();
            initEstados();
            inicial.mudaParaEstado();
            model.limpar();
        } catch (Exception ex) {
            MessageUtil.errorMessage(this, ex.getMessage());
        }
    }

    private void initEstados() {

        inicial = new EstadoInterface();
        emAdicao = new EstadoInterface();
        emEdicao = new EstadoInterface();
        emPesquisa = new EstadoInterface();

        //Estado inicial
        //habilitados
        inicial.adicionaHabilitado(txtPesquisar);
        inicial.adicionaHabilitado(btnPesquisar);
        inicial.adicionaHabilitado(btnNovo);
        inicial.adicionaHabilitado(btnSair);

        //desabilitados
        inicial.adicionaDesabilitado(btnCancelar);
        inicial.adicionaDesabilitado(btnExcluir);
        inicial.adicionaDesabilitado(btnSalvar);
        inicial.adicionaDesabilitado(txtId);
        inicial.adicionaDesabilitado(txtCategoria);

        inicial.adicionaDesabilitado(tabelaCategorias);

        //semtexto
        inicial.adicionarSemTexto(txtId);
        inicial.adicionarSemTexto(txtCategoria);


        //Estado em adição
        //habilitados

        emAdicao.adicionaHabilitado(btnSalvar);
        emAdicao.adicionaHabilitado(btnSair);
        emAdicao.adicionaHabilitado(btnCancelar);
        emAdicao.adicionaHabilitado(txtCategoria);


        //desabilitados
        emAdicao.adicionaDesabilitado(btnNovo);
        emAdicao.adicionaDesabilitado(btnExcluir);
        emAdicao.adicionaDesabilitado(btnPesquisar);
        emAdicao.adicionaDesabilitado(txtPesquisar);
        emAdicao.adicionaDesabilitado(txtId);
        emAdicao.adicionaDesabilitado(tabelaCategorias);

        //semtexto
        emAdicao.adicionarSemTexto(txtId);
        emAdicao.adicionarSemTexto(txtCategoria);

        //estado em edição
        //habilitados
        emEdicao.adicionaHabilitado(btnCancelar);
        emEdicao.adicionaHabilitado(btnExcluir);
        emEdicao.adicionaHabilitado(btnSair);
        emEdicao.adicionaHabilitado(txtCategoria);
        emEdicao.adicionaHabilitado(btnSalvar);
        emEdicao.adicionaHabilitado(btnPesquisar);

        //desabilitados
        emEdicao.adicionaDesabilitado(btnNovo);
        emEdicao.adicionaDesabilitado(txtPesquisar);
        emEdicao.adicionaDesabilitado(btnPesquisar);
        emEdicao.adicionaDesabilitado(txtId);

        //estado em pesquisa
        //habilitados
        emPesquisa.adicionaHabilitado(txtPesquisar);
        emPesquisa.adicionaHabilitado(btnPesquisar);
        emPesquisa.adicionaHabilitado(btnNovo);
        emPesquisa.adicionaHabilitado(btnSair);
        emPesquisa.adicionaHabilitado(btnCancelar);
        emPesquisa.adicionaHabilitado(tabelaCategorias);

        //desabilitados
        emPesquisa.adicionaDesabilitado(btnExcluir);
        emPesquisa.adicionaDesabilitado(btnSalvar);
        emPesquisa.adicionaDesabilitado(txtId);
        emPesquisa.adicionaDesabilitado(txtCategoria);

        //semtexto
        emPesquisa.adicionarSemTexto(txtId);
        emPesquisa.adicionarSemTexto(txtCategoria);
    }

    private void resetaEstados() {
        inicial.reset();
        emAdicao.reset();
        emEdicao.reset();
        emPesquisa.reset();
    }

    private void preencherCategoriaComCampos() {
        categoria.setCategoria(txtCategoria.getText());
    }

    private void preencheCamposComCategoria() {
        txtId.setText("" + categoria.getId());
        txtCategoria.setText("" + categoria.getCategoria());
    }

    private Map getMapaDeAtributos() {
        Map map = new HashMap();
        map.put("categoria", txtCategoria.getText());
        return map;
    }

    private void listarCategorias() throws SQLException, BuscaException {
        CategoriaDao dao = new CategoriaDao();
        cadCategorias = dao.buscarPorDescricao(txtPesquisar.getText());
        model.setCadCategorias(cadCategorias);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        PainelBotao = new javax.swing.JPanel();
        btnNovo = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        btnSalvar = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tabelaCategorias = new javax.swing.JTable();
        PainelPesquisa = new javax.swing.JPanel();
        txtPesquisar = new javax.swing.JTextField();
        btnPesquisar = new javax.swing.JButton();
        PainalCategoria = new javax.swing.JPanel();
        lblId = new javax.swing.JLabel();
        lblMarca = new javax.swing.JLabel();
        txtId = new javax.swing.JTextField();
        txtCategoria = new javax.swing.JTextField();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastro de Categorias");

        btnNovo.setText("Novo");
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnExcluir.setText("Excluir");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        btnSalvar.setText("Salvar");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnSair.setText("Sair");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout PainelBotaoLayout = new javax.swing.GroupLayout(PainelBotao);
        PainelBotao.setLayout(PainelBotaoLayout);
        PainelBotaoLayout.setHorizontalGroup(
            PainelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PainelBotaoLayout.createSequentialGroup()
                .addContainerGap(191, Short.MAX_VALUE)
                .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(160, 160, 160))
        );
        PainelBotaoLayout.setVerticalGroup(
            PainelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PainelBotaoLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(PainelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNovo)
                    .addComponent(btnCancelar)
                    .addComponent(btnExcluir)
                    .addComponent(btnSalvar)
                    .addComponent(btnSair)))
        );

        tabelaCategorias.setModel(model);
        tabelaCategorias.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaCategoriasMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tabelaCategorias);

        PainelPesquisa.setBorder(javax.swing.BorderFactory.createTitledBorder("Pesquisar Categorias"));

        btnPesquisar.setText("Pesquisar");
        btnPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPesquisarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout PainelPesquisaLayout = new javax.swing.GroupLayout(PainelPesquisa);
        PainelPesquisa.setLayout(PainelPesquisaLayout);
        PainelPesquisaLayout.setHorizontalGroup(
            PainelPesquisaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PainelPesquisaLayout.createSequentialGroup()
                .addComponent(txtPesquisar, javax.swing.GroupLayout.DEFAULT_SIZE, 615, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnPesquisar))
        );
        PainelPesquisaLayout.setVerticalGroup(
            PainelPesquisaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PainelPesquisaLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(PainelPesquisaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnPesquisar)))
        );

        PainalCategoria.setBorder(javax.swing.BorderFactory.createTitledBorder("Cadastro de Categorias"));

        lblId.setText("Codigo Categoria:");

        lblMarca.setText("Nome da Categoria:");

        txtId.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtIdActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout PainalCategoriaLayout = new javax.swing.GroupLayout(PainalCategoria);
        PainalCategoria.setLayout(PainalCategoriaLayout);
        PainalCategoriaLayout.setHorizontalGroup(
            PainalCategoriaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PainalCategoriaLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(PainalCategoriaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblMarca)
                    .addComponent(lblId))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(PainalCategoriaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtCategoria, javax.swing.GroupLayout.DEFAULT_SIZE, 584, Short.MAX_VALUE))
                .addContainerGap())
        );
        PainalCategoriaLayout.setVerticalGroup(
            PainalCategoriaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PainalCategoriaLayout.createSequentialGroup()
                .addGroup(PainalCategoriaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblId))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(PainalCategoriaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblMarca)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(PainelPesquisa, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(PainalCategoria, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(PainelBotao, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 720, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(PainelPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(PainalCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(PainelBotao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 169, Short.MAX_VALUE)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-748)/2, (screenSize.height-411)/2, 748, 411);
    }// </editor-fold>//GEN-END:initComponents

    private void txtIdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIdActionPerformed
    }//GEN-LAST:event_txtIdActionPerformed

    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        categoria = new Categoria();
        resetaEstados();
        emAdicao.mudaParaEstado();
    }//GEN-LAST:event_btnNovoActionPerformed

    private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarActionPerformed
        try {
            listarCategorias();
            resetaEstados();
            emPesquisa.mudaParaEstado();
        } catch (SQLException e) {
            MessageUtil.errorMessage(this, "Ocorreu um erro ao pesquisar");
        } catch (BuscaException ex) {
            MessageUtil.errorMessage(this, "Ocorreu um erro ao pesquisar");
        }
    }//GEN-LAST:event_btnPesquisarActionPerformed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        Validador validador = new CategoriaValidador();

        try {
            if (validador.validar(getMapaDeAtributos())) {
                preencherCategoriaComCampos();

                if (emAdicao.isEstadoAtual()) {
                    categoriaDao.criar(categoria);
                } else if (emEdicao.isEstadoAtual()) {
                    categoriaDao.atualizar(categoria);
                }
                resetaEstados();
                inicial.mudaParaEstado();
                model.limpar();
            } else {
                StringBuilder sb = new StringBuilder("Foram encontrados os seguintes erros:");

                List<String> erros = validador.getErros();
                for (String erro : erros) {
                    sb.append("\n - " + erro);
                }
                MessageUtil.errorMessage(this, sb.toString());
            }
        } catch (Exception ex) {
            MessageUtil.errorMessage(this, "Ocorreu um erro ao salvar a categoria: " + ex.getMessage());
        }
    }//GEN-LAST:event_btnSalvarActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        try {
            int resposta = JOptionPane.showConfirmDialog(this, "Deseja realmente excluir este Categoria?",
                    "Confirmação", JOptionPane.YES_NO_OPTION);

            if (resposta == JOptionPane.YES_NO_OPTION) {
                categoriaDao.deletar(categoria);
                listarCategorias();
                resetaEstados();
                inicial.mudaParaEstado();
                model.limpar();
            }
        } catch (Exception ex) {
            MessageUtil.errorMessage(this, "Ocorreu um erro ao excluir a categoria: " + ex.getMessage());
        }
    }//GEN-LAST:event_btnExcluirActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        resetaEstados();
        inicial.mudaParaEstado();
        model.limpar();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnSairActionPerformed

    private void tabelaCategoriasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaCategoriasMouseClicked
        int linha = tabelaCategorias.getSelectedRow();

        if (linha != -1) {
            categoria = model.getCategorias(linha);
            preencheCamposComCategoria();
            resetaEstados();
            emEdicao.mudaParaEstado();
        }
    }//GEN-LAST:event_tabelaCategoriasMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel PainalCategoria;
    private javax.swing.JPanel PainelBotao;
    private javax.swing.JPanel PainelPesquisa;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnPesquisar;
    private javax.swing.JButton btnSair;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel lblId;
    private javax.swing.JLabel lblMarca;
    private javax.swing.JTable tabelaCategorias;
    private javax.swing.JTextField txtCategoria;
    private javax.swing.JTextField txtId;
    private javax.swing.JTextField txtPesquisar;
    // End of variables declaration//GEN-END:variables
}
